<?php
class Code{
    //验证码的宽度
    private $width;
    //高度
    private $height;
    //背景色
    private $bgColor;
    //图像资源
    private $img;
    //验证码长度
    private $len;
    //验证码字体大小
    private $fontSize;
    //验证码种子
    private $seek = '1234567890qwertyuioasdfghjklzxcvbnm';

    /**
     * Code 构造方法.
     * @param null $width
     */
    public function __construct($width=NULL,$height=NULL,$bgColor=NULL,$len=NULL,$fontSize=NULL)
    {
        $this->width = is_null($width) ? 200 : $width;
        $this->height = is_null($height) ? 60 : $height;
        $this->bgColor = is_null($bgColor) ? '#cccccc' : $bgColor;
        $this->len = is_null($len) ? 4 : $len;
        $this->fontSize = is_null($fontSize) ? 30 : $fontSize;

    }

    /**
     * 生成验证码
     */
    public function make(){
        //1.发送头部
        header('Content-type:image/png');
        //2.创建画布,然后填充
        $this->createBg();
        //3.写字
        $this->write();
        //4.干扰
        $this->makeTrouble();
        //5.输出显示
        imagepng($this->img);
        //6.销毁
        imagedestroy($this->img);
    }
    //干扰
    private function makeTrouble(){
        for ($i = 0; $i<10;$i++){
            $color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
        }
    }
    //写字
    private function write(){
        for ($i = 0; $i < $this->len; $i++){
            $x = $this->width / $this->len * $i + 10;
            $y = ($this->height + $this->fontSize) / 2;
            $color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            //$this->seek = 'abcd';
            //随机拿到其中的字符串 $this->seek[mt_rand(0,长度-1)]
            $text = $this->seek[mt_rand(0,strlen($this->seek)-1)];
            imagettftext($this->img,$this->fontSize,mt_rand(-45,45),$x,$y,$color,'./Tool/font.ttf',$text);
        }
    }

    /**
     * 创建背景,并且填充
     */
    private function createBg(){
        $img = imagecreatetruecolor($this->width,$this->height);
        $color = hexdec($this->bgColor);
        imagefill($img,0,0,$color);
        $this->img = $img;
    }


}
$code = new Code();
$code->make();